package spring.framework.beans.factory.support;

import spring.framework.beans.BeansException;
import spring.framework.beans.factory.DisposableBean;
import spring.framework.beans.factory.config.SingletonBeanRegistry;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fun.pengzh
 * @class spring.framework.beans.factory.support.DefaultSingletonBeanRegistry
 * @desc 默认注册器
 * @since 2021-10-10
 */
public class DefaultSingletonBeanRegistry implements SingletonBeanRegistry {

    private Map<String, Object> singletonObjects = new HashMap<>();

    private Map<String, DisposableBean> disposableBeanMap = new HashMap<>();

    @Override
    public Object getSingleton(String beanName) {
        return singletonObjects.get(beanName);
    }

    protected void addSingleton(String beanName, Object singletonBean) {
        singletonObjects.put(beanName, singletonBean);
    }

    public void registerDisposableBean(String beanName, DisposableBean disposableBean) {
        disposableBeanMap.put(beanName, disposableBean);
    }

    public void destroySingletons() {
        Object[] disposableBeans = disposableBeanMap.keySet().toArray();
        for (int i = disposableBeans.length-1; i >= 0; i--) {
            Object disposableBean = disposableBeans[i];
            DisposableBean bean = disposableBeanMap.remove(disposableBean);
            try {
                bean.destroy();
            } catch (Exception e) {
                throw new BeansException("Destroy method on bean with name '" + disposableBean + "' threw an exception", e);
            }
        }
    }

}
